package com.wzcl.app.controller;

import com.qiniu.common.QiniuException;
import com.wzcl.app.config.QiNiuConfig;
import com.wzcl.app.dao.model.AppFile;
import com.wzcl.app.model.common.BusinessException;
import com.wzcl.app.model.common.CodeMsg;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.model.dto.FileDto;
import com.wzcl.app.service.AppFileService;
import com.wzcl.app.service.common.QiNiuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

@Log4j2
@RestController
@RequestMapping("/file")
@Api(value = "文件上传controller", tags = {"文件上传接口"})
public class FileController {

    @Resource
    private QiNiuService qiNiuService;
    @Resource
    private AppFileService appFileService;

    @PostMapping("/uploadToken")
    public String uploadToken(){
        return qiNiuService.uploadToken();
    }

    @PostMapping("/download")
    public String download(@RequestBody FileDto file) throws UnsupportedEncodingException {
        AppFile appFile = appFileService.getFileByKey(file.getFileKey());
        if(appFile == null){
            throw new BusinessException(CodeMsg.FILE_NOT_EXIST);
        }
        return qiNiuService.downLoad(appFile.getFileKey());
    }

    @GetMapping("/exist/{MD5}")
    public boolean exist(@PathVariable String MD5){
        AppFile file = appFileService.getFileByKey(MD5);
        return file!=null;
    }


    @DeleteMapping("/delete/list")
    @ApiOperation("批量删除七牛云文件")
    public RVO deleteListFromQiNiu(@RequestBody List<String> list) throws QiniuException {
        HashMap hashMap = qiNiuService.deleteByListFromQiNiu(list);
        return RVO.success(hashMap);
    }

    @DeleteMapping("/delete")
    @ApiOperation("单独删除七牛云文件")
    public RVO deleteFromQiNiu(@RequestBody String fileName) {
        int code = qiNiuService.deleteByFile(fileName);
        if (code != -1){
            return RVO.success("删除成功");
        }
        return RVO.error("删除文件失败");
    }
}
